package com.passer.labyrinth.core.util;

import com.passer.labyrinth.core.contant.CellType;

import java.util.Random;

public class MazeUtils {

    // 初始化迷宫，所有格子设为墙壁
    public static void initializeMaze(CellType[][] maze) {
        for (int i = 0; i < maze.length; i++) {
            for (int j = 0; j < maze[0].length; j++) {
                maze[i][j] = CellType.WALL;
            }
        }
    }

    // 深度优先搜索生成迷宫
    public static void generateMazeDFS(CellType[][] maze, int x, int y) {
        int[][] directions = {{-2, 0}, {2, 0}, {0, -2}, {0, 2}};
        shuffleArray(directions);

        for (int[] dir : directions) {
            int newX = x + dir[0];
            int newY = y + dir[1];

            if (newX >= 0 && newX < maze.length && newY >= 0 && newY < maze[0].length && maze[newX][newY] == CellType.WALL) {
                maze[x + dir[0] / 2][y + dir[1] / 2] = CellType.ROAD;
                maze[newX][newY] = CellType.ROAD;
                generateMazeDFS(maze, newX, newY);
            }
        }
    }

    // 随机打乱数组顺序（Fisher-Yates Shuffle）
    private static void shuffleArray(int[][] array) {
        Random random = new Random();
        for (int i = array.length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            int[] temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }

    // 查找指定字符的位置
    public static int[] findPosition(CellType[][] maze, CellType target) {
        for (int i = 0; i < maze.length; i++) {
            for (int j = 0; j < maze[0].length; j++) {
                if (maze[i][j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        throw new RuntimeException("迷宫中未找到'" + target + "'!");
    }
}
